package com.example.common.aop;


import com.alibaba.fastjson.JSON;
import com.example.common.entity.LogOperation;
import com.example.common.mapper.LogOperationMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 切面处理类，操作日志异常日志记录处理
 * @author YanMing
 */
@Aspect
@Component
public class LogOperationAspect extends LogAspect{
    @Resource
    private LogOperationMapper logOperationMapper;

    /**
     * 设置操作日志切入点 记录操作日志 在注解的位置切入代码
     */
    @Pointcut("@annotation(com.example.common.annotation.OperationLog)")
    public void operationLogPoinCut() {
    }

    /**
     * 设置操作切入点记录日志 扫描所有controller包下操作
     */
    @Pointcut("execution(* com.example.controller..*.*(..))")
    public void operationLogControllerPoinCut() {
    }

    /**
     * 正常返回通知，拦截用户操作日志，连接点正常执行完成后执行， 如果连接点抛出异常，则不会执行
     *
     * @param joinPoint 切入点
     * @param result    返回结果
     */
    @AfterReturning(value = "operationLogPoinCut()", returning = "result")
    public void saveAnnotationOperLog(JoinPoint joinPoint, Object result) {
        createLogOperation(joinPoint, result);

    }


    @AfterReturning(value = "operationLogControllerPoinCut()", returning = "result")
    public void saveControllerOperLog(JoinPoint joinPoint, Object result) {
        createLogOperation(joinPoint, result);

    }


    private void createLogOperation(JoinPoint joinPoint, Object result) {
        LogOperation log = (LogOperation) createLog(joinPoint, new LogOperation());
        // 返回结果
        log.setResponseParams(JSON.toJSONString(result));
        logOperationMapper.insert(log);
    }

}
